package com.wande.dataplatform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wande.common.core.exception.ServiceException;
import com.wande.common.mybatis.core.page.PageQuery;
import com.wande.common.mybatis.core.page.TableDataInfo;
import com.wande.common.satoken.utils.LoginHelper;
import com.wande.dataplatform.domain.AssetTagRelation;
import com.wande.dataplatform.domain.DataTag;
import com.wande.dataplatform.domain.bo.DataTagBo;
import com.wande.dataplatform.domain.dto.TagRelationDTO;
import com.wande.dataplatform.domain.dto.TagStatisticsDTO;
import com.wande.dataplatform.domain.vo.DataTagVO;
import com.wande.dataplatform.mapper.AssetTagRelationMapper;
import com.wande.dataplatform.mapper.DataTagMapper;
import com.wande.dataplatform.service.IDataTagService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据标签服务实现
 *
 * @author wande
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DataTagServiceImpl implements IDataTagService {

    private final DataTagMapper dataTagMapper;
    private final AssetTagRelationMapper assetTagRelationMapper;

    @Override
    public List<DataTagVO> selectTagTree(Long projectId) {
        String tenantId = LoginHelper.getTenantId();
        List<DataTagVO> allTags = dataTagMapper.selectTagTree(Long.parseLong(tenantId), projectId);
        return buildTree(allTags, 0L);
    }

    /**
     * 构建树形结构
     */
    private List<DataTagVO> buildTree(List<DataTagVO> allTags, Long parentId) {
        List<DataTagVO> tree = new ArrayList<>();
        for (DataTagVO tag : allTags) {
            if (ObjectUtil.equal(tag.getParentId(), parentId)) {
                List<DataTagVO> children = buildTree(allTags, tag.getId());
                if (CollUtil.isNotEmpty(children)) {
                    tag.setChildren(children);
                }
                tree.add(tag);
            }
        }
        return tree;
    }

    @Override
    public TableDataInfo<DataTagVO> selectTagList(DataTagBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DataTag> wrapper = Wrappers.lambdaQuery(DataTag.class)
            .like(ObjectUtil.isNotEmpty(bo.getTagName()), DataTag::getTagName, bo.getTagName())
            .eq(ObjectUtil.isNotEmpty(bo.getTagType()), DataTag::getTagType, bo.getTagType())
            .eq(ObjectUtil.isNotEmpty(bo.getStatus()), DataTag::getStatus, bo.getStatus())
            .eq(ObjectUtil.isNotEmpty(bo.getProjectId()), DataTag::getProjectId, bo.getProjectId())
            .orderByAsc(DataTag::getSortOrder)
            .orderByDesc(DataTag::getCreateTime);

        Page<DataTagVO> page = dataTagMapper.selectVoPage(pageQuery.build(), wrapper);
        return TableDataInfo.build(page);
    }

    @Override
    public DataTagVO selectTagById(Long id) {
        DataTagVO vo = dataTagMapper.selectVoById(id);
        if (vo == null) {
            throw new ServiceException("标签不存在");
        }
        // 查询关联资产数量
        Long assetCount = dataTagMapper.countAssetsByTagId(id);
        vo.setAssetCount(assetCount);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createTag(DataTagBo bo) {
        // 检查编码是否重复
        Long count = dataTagMapper.selectCount(Wrappers.lambdaQuery(DataTag.class)
            .eq(DataTag::getTagCode, bo.getTagCode()));
        if (count > 0) {
            throw new ServiceException("标签编码已存在");
        }

        DataTag tag = BeanUtil.toBean(bo, DataTag.class);
        
        // 设置层级
        if (bo.getParentId() != null && bo.getParentId() > 0) {
            DataTag parent = dataTagMapper.selectById(bo.getParentId());
            if (parent == null) {
                throw new ServiceException("父标签不存在");
            }
            tag.setTagLevel(parent.getTagLevel() + 1);
        } else {
            tag.setParentId(0L);
            tag.setTagLevel(1);
        }

        if (tag.getStatus() == null) {
            tag.setStatus(1);
        }
        if (tag.getUsageCount() == null) {
            tag.setUsageCount(0L);
        }

        dataTagMapper.insert(tag);
        return tag.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTag(DataTagBo bo) {
        DataTag tag = dataTagMapper.selectById(bo.getId());
        if (tag == null) {
            throw new ServiceException("标签不存在");
        }

        // 检查编码是否重复
        Long count = dataTagMapper.selectCount(Wrappers.lambdaQuery(DataTag.class)
            .eq(DataTag::getTagCode, bo.getTagCode())
            .ne(DataTag::getId, bo.getId()));
        if (count > 0) {
            throw new ServiceException("标签编码已存在");
        }

        BeanUtil.copyProperties(bo, tag, "id", "usageCount", "createTime", "createBy");
        return dataTagMapper.updateById(tag) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTag(Long id) {
        // 检查是否有子标签
        Long childCount = dataTagMapper.countChildren(id);
        if (childCount > 0) {
            throw new ServiceException("存在子标签，无法删除");
        }

        // 检查是否有关联资产
        Long assetCount = dataTagMapper.countAssetsByTagId(id);
        if (assetCount > 0) {
            throw new ServiceException("标签已关联资产，无法删除");
        }

        return dataTagMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTags(List<Long> ids) {
        for (Long id : ids) {
            deleteTag(id);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addTagsToAsset(TagRelationDTO dto) {
        String tenantIdStr = LoginHelper.getTenantId();
        Long tenantId = Long.parseLong(tenantIdStr);
        Long userId = LoginHelper.getUserId();

        // 先删除已有关联
        assetTagRelationMapper.deleteByAsset(dto.getAssetId(), dto.getAssetType());

        // 批量插入新关联
        for (Long tagId : dto.getTagIds()) {
            AssetTagRelation relation = new AssetTagRelation();
            relation.setTenantId(tenantId);
            relation.setAssetId(dto.getAssetId());
            relation.setAssetType(dto.getAssetType());
            relation.setTagId(tagId);
            relation.setTagSource("MANUAL");
            relation.setCreateBy(userId);
            assetTagRelationMapper.insert(relation);

            // 更新标签使用次数
            incrementUsageCount(tagId);
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeTagsFromAsset(Long assetId, String assetType, List<Long> tagIds) {
        for (Long tagId : tagIds) {
            assetTagRelationMapper.delete(Wrappers.lambdaQuery(AssetTagRelation.class)
                .eq(AssetTagRelation::getAssetId, assetId)
                .eq(AssetTagRelation::getAssetType, assetType)
                .eq(AssetTagRelation::getTagId, tagId));
        }
        return true;
    }

    @Override
    public List<DataTagVO> selectTagsByAsset(Long assetId, String assetType) {
        List<Long> tagIds = assetTagRelationMapper.selectTagIdsByAsset(assetId, assetType);
        if (CollUtil.isEmpty(tagIds)) {
            return new ArrayList<>();
        }

        return dataTagMapper.selectVoByIds(tagIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean autoTagAsset(Long assetId, String assetType) {
        // 查询所有启用的自动标签规则
        List<DataTag> autoTags = dataTagMapper.selectList(Wrappers.lambdaQuery(DataTag.class)
            .isNotNull(DataTag::getAutoTagRule)
            .eq(DataTag::getStatus, 1));

        if (CollUtil.isEmpty(autoTags)) {
            return true;
        }

        String tenantIdStr = LoginHelper.getTenantId();
        Long tenantId = Long.parseLong(tenantIdStr);
        Long userId = LoginHelper.getUserId();

        // 根据规则自动打标签
        for (DataTag tag : autoTags) {
            // TODO: 实现自动打标签逻辑，根据规则判断是否应该打标签
            // 这里简化处理，实际应该解析 autoTagRule 并执行规则匹配
            boolean shouldTag = evaluateAutoTagRule(tag.getAutoTagRule(), assetId, assetType);
            
            if (shouldTag) {
                // 检查是否已存在关联
                Long count = assetTagRelationMapper.selectCount(Wrappers.lambdaQuery(AssetTagRelation.class)
                    .eq(AssetTagRelation::getAssetId, assetId)
                    .eq(AssetTagRelation::getAssetType, assetType)
                    .eq(AssetTagRelation::getTagId, tag.getId()));

                if (count == 0) {
                    AssetTagRelation relation = new AssetTagRelation();
                    relation.setTenantId(tenantId);
                    relation.setAssetId(assetId);
                    relation.setAssetType(assetType);
                    relation.setTagId(tag.getId());
                    relation.setTagSource("AUTO");
                    relation.setCreateBy(userId);
                    assetTagRelationMapper.insert(relation);

                    // 更新标签使用次数
                    incrementUsageCount(tag.getId());
                }
            }
        }

        return true;
    }

    /**
     * 评估自动标签规则
     */
    private boolean evaluateAutoTagRule(String ruleJson, Long assetId, String assetType) {
        // TODO: 实现规则引擎，解析 JSON 规则并执行匹配
        // 规则示例：{"field": "name", "operator": "contains", "value": "test"}
        // 这里简化处理，返回 false
        return false;
    }

    @Override
    public List<TagStatisticsDTO> selectTagStatistics() {
        String tenantIdStr = LoginHelper.getTenantId();
        Long tenantId = Long.parseLong(tenantIdStr);
        return assetTagRelationMapper.selectTagStatistics(tenantId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void incrementUsageCount(Long tagId) {
        DataTag tag = dataTagMapper.selectById(tagId);
        if (tag != null) {
            tag.setUsageCount(tag.getUsageCount() + 1);
            dataTagMapper.updateById(tag);
        }
    }
}
